#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Build script for creating executable from Hash Storage GUI
"""

import os
import sys
import subprocess
from pathlib import Path

def install_pyinstaller():
    """Install PyInstaller if not already installed"""
    try:
        import PyInstaller
        print("PyInstaller is already installed.")
    except ImportError:
        print("Installing PyInstaller...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
        print("PyInstaller installed successfully.")

def build_exe():
    """Build executable using PyInstaller"""
    # Ensure PyInstaller is installed
    install_pyinstaller()
    
    # Get current directory
    current_dir = Path(__file__).parent
    gui_file = current_dir / "gui.py"
    
    if not gui_file.exists():
        print(f"Error: {gui_file} not found!")
        return False
    
    # PyInstaller command
    cmd = [
        "pyinstaller",
        "--onefile",  # Create a single executable file
        "--windowed",  # Hide console window (for GUI apps)
        "--name=HashStorage",  # Name of the executable
        "--icon=gui_ico.ico" if (current_dir / "gui_ico.ico").exists() else "",  # Icon if available
        "--add-data=requirements.txt;.",  # Include requirements.txt
        "--hidden-import=PyQt5.QtCore",
        "--hidden-import=PyQt5.QtGui", 
        "--hidden-import=PyQt5.QtWidgets",
        "--hidden-import=requests",
        "--hidden-import=pathlib",
        str(gui_file)
    ]
    
    # Remove empty icon parameter if no icon file
    cmd = [arg for arg in cmd if arg]
    
    print("Building executable...")
    print(f"Command: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, cwd=current_dir, check=True)
        print("\nBuild completed successfully!")
        
        # Check if executable was created
        exe_path = current_dir / "dist" / "HashStorage.exe"
        if exe_path.exists():
            print(f"Executable created at: {exe_path}")
            print(f"File size: {exe_path.stat().st_size / (1024*1024):.1f} MB")
        else:
            print("Warning: Executable not found in expected location.")
            
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"Build failed with error: {e}")
        return False
    except Exception as e:
        print(f"Unexpected error: {e}")
        return False

def clean_build():
    """Clean build artifacts"""
    current_dir = Path(__file__).parent
    
    # Directories to clean
    clean_dirs = ["build", "dist", "__pycache__"]
    
    for dir_name in clean_dirs:
        dir_path = current_dir / dir_name
        if dir_path.exists():
            print(f"Cleaning {dir_path}...")
            import shutil
            shutil.rmtree(dir_path)
    
    # Clean .spec files
    for spec_file in current_dir.glob("*.spec"):
        print(f"Removing {spec_file}...")
        spec_file.unlink()
    
    print("Clean completed.")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Build Hash Storage GUI executable")
    parser.add_argument("--clean", action="store_true", help="Clean build artifacts")
    parser.add_argument("--build", action="store_true", help="Build executable")
    
    args = parser.parse_args()
    
    if args.clean:
        clean_build()
    elif args.build:
        build_exe()
    else:
        # Default: clean then build
        print("Cleaning previous build...")
        clean_build()
        print("\nBuilding executable...")
        success = build_exe()
        
        if success:
            print("\n" + "="*50)
            print("BUILD SUCCESSFUL!")
            print("="*50)
            print("The executable is located in the 'dist' folder.")
            print("You can distribute the HashStorage.exe file independently.")
        else:
            print("\n" + "="*50)
            print("BUILD FAILED!")
            print("="*50)
            print("Please check the error messages above.")